package com.sdry.web.controller.jyy.test;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sdry.model.jyy.SolidPosition;
import com.sdry.service.jyy.SolidServise;
import com.sdry.utils.ResponseUtil;


/**
 * @ClassName:    [SerialComm4MainWindows]   
 * @Description:  [串口测试]   
 * @Author:       [jyy]   
 * @CreateDate:   [2018年12月24日 上午10:24:52]    
 * @Version:      [v1.0]
 */
@Controller
public class SerialComm2 implements ApplicationListener<ContextRefreshedEvent> {
	
	@Resource
	private SolidServise solidServise;
	
	private static final Log LOGGER = LogFactory.getLog(SerialComm2.class);
	
	public static String SOLID= "0";
	public static String CUT = "0";
	public static int SOLID_COUNT = 0;
	public static int CUT_COUNT = 0;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			if (event.getApplicationContext().getParent() == null) {
				// 需要实现的功能
				System.out.println("固化监听器启动。。。。");
				try {
					connect("COM9");

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			LOGGER.error("StartGateServiceData", e);
		}
	}

	private static SerialPort serialPort;

	/**
	 * 链接硬件
	 * @param portName 串口名称
	 * @throws Exception
	 */
	public void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
			if (commPort instanceof SerialPort) {
				serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				
				(new Thread(new SerialReader(in))).start();
				
				byte[] buffer = new byte[1024];
				System.out.println("============="+in.read(buffer));
			} else {
				System.out.println("Error: Only serial ports are handled by this example.");
			}
		}
	}


	/** 读串口数据*/
	public class SerialReader implements Runnable {
		InputStream in;
		public SerialReader(InputStream in) {
			this.in = in;
		}
		public void run() {
			
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					String getValue = new String(buffer, 0, len);
					if(getValue != null && getValue != "" && getValue.length() > 2) {
						System.out.println(getValue);
					}
					
					if(getValue.contains("bunding")) {
						SOLID = "0";
						writeFile("bunding.properties","1");
					}else if (getValue.contains("cut")) {
						CUT = "0";
						writeFile("cut.properties","1");
					}else if(getValue.contains("solid")) {
						//String getValue = "solid:A3,T003";
						String sub1 = getValue.substring(6, 8);//A3
						String sub2 = getValue.substring(9, 13);//T003
						System.out.println(sub1);
						System.out.println(sub2);
						SolidPosition solidPosition = new SolidPosition();
						solidPosition.setPosition(sub1);
						solidPosition.setTc(sub2);
						solidServise.editPosition(solidPosition);
					}else if(getValue.contains("over")) {
						//String getValue = "over:A3,T003";
						String sub1 = getValue.substring(5, 7);//A3
						System.out.println(sub1);
					
					solidServise.editPosition2(sub1);
					}else if (getValue.contains("arrive")) {
						writeFile("arrive.properties","1");
					}else {
						
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	

	/**
	 * 拆端盖工位呼叫AGV
	 * @param tc  台车条码
	 */
	public static int sendMsg(String tc){
		int flag = 0;
        try {
        	OutputStream outputStream = serialPort.getOutputStream();
			outputStream.write(("bunding").getBytes("GB2312"));
			SOLID = "1";
			flag = 1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        return flag;
	}
	
	
	/**
	 * 固化开始扫码回馈
	 * @param state 扫码状态
	 * @param msg 错误信息
	 */
	public static int sendMsg2(String state){
		int flag = 0;
     	 try {
         	OutputStream outputStream = serialPort.getOutputStream();
         	outputStream.write((state).getBytes("GB2312"));
         	flag = 1;
 		} catch (UnsupportedEncodingException e) {
 			e.printStackTrace();
 		} catch (IOException e) {
 			e.printStackTrace();
 		}
     	 
     	return flag;
	}
	
	
	/**
	 * 切割呼叫Agv
	 * @param tc
	 */
	public static int sendMsgCut(String tc){
		int flag = 0;
		 try {
	        	OutputStream outputStream = serialPort.getOutputStream();
				outputStream.write(("cut").getBytes("GB2312"));
				flag = 1;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		 return flag;
	}
	
	/**
	 * 固化agv拉动
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/solidAgv")
	public void solidAgv(HttpServletResponse response,String tc) throws Exception {
		//(new SerialComm2()).connect("COM9");
		int sendMsg = SerialComm2.sendMsg(tc);
		ResponseUtil.write(response, sendMsg);
	}
	
	/**
	 * 通知agv固化工位扫码结果
	 */
	@RequestMapping("solidNotifyAgv")
	public void solidNotifyAgv(int flag) {
		if(flag == 1) {
			 SerialComm2.sendMsg2("success");
			 //将小车状态改成未到
			 writeFile("arrive.properties","2");
		}else if(flag == 2) {
			SerialComm2.sendMsg2("fail");
			 //将小车状态改成未到
			writeFile("arrive.properties","2");
		}else{
			SerialComm2.sendMsg2("warning");
			 //将小车状态改成未到
			writeFile("arrive.properties","2");
		}
	}
	
	/**
	 * agv拉动
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/cutAgv")
	public void agv(HttpServletResponse response) throws Exception{
		
		int sendMsgCut = sendMsgCut("T003");
		ResponseUtil.write(response, sendMsgCut);
	}
	
	 public void writeFile(String name, String msg) {
	    String path = ReadTxt.class.getClassLoader().getResource(name).getPath();
	        try {
	            File writeName = new File(path); // 相对路径，如果没有则要建立一个新的output.txt文件
	            writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
	            try (FileWriter writer = new FileWriter(writeName);
	                 BufferedWriter out = new BufferedWriter(writer)
	            ) {
	                out.write(msg); // \r\n即为换行
	                out.flush(); // 把缓存区内容压入文件
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	 
	 
 	/**
	 * 读取小车到了没
 	 * @throws Exception 
	 */
	@RequestMapping("/arriveReade")
	public void arriveReade(HttpServletResponse response) throws Exception {
		String pathname = ReadTxt.class.getClassLoader().getResource("arrive.properties").getPath();
        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader) 
        ) {
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                ResponseUtil.write(response, line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	@RequestMapping("getCut")
	public void getCut(HttpServletResponse response) throws Exception {
		String pathname = ReadTxt.class.getClassLoader().getResource("cut.properties").getPath();
        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader) 
        ) {
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                ResponseUtil.write(response, line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	@RequestMapping("setCut")
	public void setCut(HttpServletResponse response) throws Exception {
		writeFile("cut.properties","0");
	}
	
	@RequestMapping("getBunding")
	public void getBunding(HttpServletResponse response) throws Exception {
		String pathname = ReadTxt.class.getClassLoader().getResource("bunding.properties").getPath();
		try (FileReader reader = new FileReader(pathname);
				BufferedReader br = new BufferedReader(reader) 
				) {
			String line;
			//网友推荐更加简洁的写法
			while ((line = br.readLine()) != null) {
				// 一次读入一行数据
				ResponseUtil.write(response, line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("setBunding")
	public void setBunding(HttpServletResponse response) throws Exception {
		writeFile("bunding.properties","0");
	}
	 

	public static void main(String[] args)  {
		try {
			//sendMsg2("COM3", "成功", "请通过");
			//sendMsg2("COM3", "失败", "请联系管理员");
			//(new SerialComm2()).connect("COM9");
			/*int sendMsg = sendMsg("T001");
			System.out.println(sendMsg);*/
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
